﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SlimDX;

namespace Gype.GUI.Components
{
    public abstract class ItemsControl : Component
    {
        protected List<Component> mChildren = new List<Component>();

        public void addChild(Component component)
        {
            mChildren.Add(component);
            component.AttachedToManager(mGUIManager);
            component.attachedToParent(this);
        }

        public void removeChild(Component child)
        {

        }

        internal override void OnMessage(ControlMessage message)
        {
            base.OnMessage(message);

            for (int i = mChildren.Count - 1; i >= 0; --i)
                message.ForwardMessage(this, mChildren[i]);
        }

        internal int extendNCArea(float dx, float dy)
        {
            int start = mNCExtentMap.Count;
            while (mNCExtentMap.ContainsKey(start))
            {
                ++start;
            }

            mNCExtentMap.Add(start, mNCExtent);

            mNCExtent.X += dx;
            mNCExtent.Y += dy;

            return start;
        }

        internal Vector2 getNCExtent(int key)
        {
            if (mNCExtentMap.ContainsKey(key) == false)
            {
                return Vector2.Zero;
            }

            Vector2 nc = mNCExtentMap[key];
            return nc - mNCExtent;
        }

        internal Vector2 getClientSize()
        {
            var childOfs = getChildOffset();
            return new Vector2(Size.Width - mNCExtent.X - childOfs.X * 2, Size.Height - mNCExtent.Y - childOfs.Y);
        }

        protected virtual void renderChildren()
        {
            var target = mGUIManager.Target;
            var oldTransform = target.Transform;
            var childPos = getChildOffset();

            target.Transform *= Gype.UI.LinearMatrix.Translation(Location.X + childPos.X, Location.Y + childPos.Y);

            foreach (var child in mChildren)
                child.RenderObject();

            target.Transform = oldTransform;
        }

        protected virtual void renderChildrenTopLevel()
        {
            var target = mGUIManager.Target;
            var oldTransform = target.Transform;
            var childPos = getChildOffset();

            target.Transform *= Gype.UI.LinearMatrix.Translation(Location.X + childPos.X, Location.Y + childPos.Y);

            foreach (var child in mChildren)
                child.RenderTopLevel();

            target.Transform = oldTransform;
        }

        protected Vector2 mNCExtent = Vector2.Zero;
        protected Dictionary<int, Vector2> mNCExtentMap = new Dictionary<int, Vector2>();
    }
}
